package com.yuji.aacar.controller.address.newaddress;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.yuji.aacar.R;
import com.yuji.aacar.base.BaseActivity;
import com.yuji.aacar.base.Const;
import com.yuji.aacar.base.EventConst;
import com.yuji.aacar.base.UserCenter;
import com.yuji.aacar.bean.beans.QueryCarAddressInfo;
import com.yuji.aacar.bean.beans.Room;
import com.yuji.aacar.bean.response.LoginResponse;
import com.yuji.aacar.bean.response.ManagerCarAddressResponse;
import com.yuji.aacar.controller.address.roomaddress.RoomAddressActivity;
import com.yuji.aacar.core.cores.event.CoreEventCenter;
import com.yuji.aacar.core.cores.services.CoreServiceResponse;
import com.yuji.aacar.core.cores.utils.LogUtil;
import com.yuji.aacar.service.BaseServiceMediator;
import com.yuji.aacar.service.BaseServiceParams;
import com.yuji.aacar.widgets.autolayout.AutoRelativeLayout;
import com.yuji.aacar.widgets.canceledit.CancelEditText;
import com.yuji.aacar.widgets.tagview.AutoFlowLayout;
import com.yuji.aacar.widgets.textview.PingFangTextView;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.yuji.aacar.base.UserCenter.getCurrentUser;


public class NewAddressActivity extends BaseActivity {


    NewAddressActivityVM newAddressActivityVM;
    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.back_image)
    AutoRelativeLayout backImage;
    @BindView(R.id.title_content)
    PingFangTextView titleContent;
    @BindView(R.id.back_login)
    PingFangTextView backLogin;
    @BindView(R.id.title_message_iv)
    ImageView titleMessageIv;
    @BindView(R.id.title_message_rl)
    AutoRelativeLayout titleMessageRl;
    @BindView(R.id.title_rl)
    AutoRelativeLayout titleRl;
    @BindView(R.id.new_address_contact_name)
    CancelEditText newAddressContactName;
    @BindView(R.id.new_address_contact_phone)
    CancelEditText newAddressContactPhone;
    @BindView(R.id.new_address_arrow)
    ImageView newAddressArrow;
    @BindView(R.id.about_score)
    AutoRelativeLayout aboutScore;
    @BindView(R.id.new_address_contact_address)
    CancelEditText newAddressContactAddress;
    @BindView(R.id.new_address_tag_flow_layout)
    AutoFlowLayout flowLayout;
    @BindView(R.id.new_address_contact_submit)
    Button newAddressContactSubmit;
    @BindView(R.id.new_address_tag_name)
    PingFangTextView newAddressTagName;
    @BindView(R.id.new_address_new_tag_et)
    EditText newAddressNewTagEt;
    @BindView(R.id.new_address_new_tag_confirm)
    TextView newAddressNewTagConfirm;
    @BindView(R.id.room_address)
    PingFangTextView roomAddress;

    private  LoginResponse user;

    private int count = 2;

    private AutoRelativeLayout lastLayout;
    private String tagStr;
    private boolean isSame = false;

    private Room selectedRoom;
    private String contectName;
    private String contectNo;
    private String roomStr;
    private String addressDetail;

    private QueryCarAddressInfo addressInfo;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_new_address);
        ButterKnife.bind(this);
        addressInfo = (QueryCarAddressInfo) getIntent().getSerializableExtra("QueryCarAddressInfo");
        if (null != addressInfo) {
            initTitle(true, "编辑洗车地址", null);
            newAddressContactSubmit.setText("保存");
        } else {
            initTitle(true, "新增洗车地址", null);
        }

        super.onCreate(savedInstanceState);
        initTag();

        flowLayout.setOnItemClickListener(new AutoFlowLayout.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View view) {

                AutoRelativeLayout clickLayout = (AutoRelativeLayout) view.findViewById(R.id.new_address_tag_layout);
                clickLayout.setBackgroundResource(R.drawable.selector_white_layout_select);
                tagStr = ((TextView) view.findViewById(R.id.new_address_tag_item_tv)).getText().toString();

                if (null == lastLayout) {
                    lastLayout = clickLayout;
                } else {
                    if (lastLayout != clickLayout) {
                        lastLayout.setBackgroundResource(R.drawable.selector_white_layout_normal);
                        lastLayout = clickLayout;
                        isSame = false;
                    } else {
                        if (isSame) {
                            lastLayout.setBackgroundResource(R.drawable.selector_white_layout_normal);
                            isSame = false;
                        } else {
                            lastLayout.setBackgroundResource(R.drawable.selector_white_layout_select);
                            isSame = true;
                        }
                    }
                }
            }
        });

        if (null != addressInfo) {
            initUI();
        }

    }
    private ArrayList<String> mDatas = new ArrayList<>();
//    private String[] mDatas = new String[]{
//            "家",
//            "公司"
//    };

    private void initTag() {
        user = getCurrentUser();
        if (null != user) {
            String tags = UserCenter.getTags(user.getMemberId());
            if (!TextUtils.isEmpty(tags) ){
                if (tags.contains("------")){
                    String[] datas = tags.split("------");
                    for (int i = 0; i < datas.length; i++) {
                        mDatas.add(datas[i]);
                    }
                } else {
                    mDatas.add(tags);
                }
            } else {
                mDatas.add("家");
                mDatas.add("公司");
            }
        }

        for (int i = 0; i < mDatas.size(); i++) {
            View item = mLayoutInflater.inflate(R.layout.activity_new_address_tag, null);
            TextView tvAttrTag = (TextView) item.findViewById(R.id.new_address_tag_item_tv);
            tvAttrTag.setText(mDatas.get(i));
            tvAttrTag.setTag(i);
            flowLayout.addView(item);
        }


    }

    @Override
    public void onResume() {
        super.onResume();
        user = getCurrentUser();
    }

    @OnClick({R.id.new_address_new_tag_confirm, R.id.new_address_contact_submit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.new_address_new_tag_confirm:
                String str = newAddressNewTagEt.getText().toString();
                if (!TextUtils.isEmpty(str)){
                    flowLayout.setLineCenter(false);
                    View item = mLayoutInflater.inflate(R.layout.activity_new_address_tag, null);
                    //                item.findViewById(R.id.new_address_tag_layout);
                    TextView tvAttrTag = (TextView) item.findViewById(R.id.new_address_tag_item_tv);
                    tvAttrTag.setText(str);
                    flowLayout.setSingleLine(false);
                    flowLayout.setMaxLines(Integer.MAX_VALUE);
                    flowLayout.addView(item);
                    count++;
                    mDatas.add(str);
                    saveTagSting();

                } else {
                    showToast("请填写标签名称，最多5个字");
                }
                break;
            case R.id.new_address_contact_submit:
                if (isLegal()) {
                    if (null != addressInfo){
                        requestParams = BaseServiceParams.managerCarAddress(
                                tagStr, addressInfo.getAreaCode(),
                                addressInfo.getAreaName(), addressInfo.getCityCode(),
                                addressInfo.getCityName(), contectName,
                                contectNo, addressDetail, addressInfo.getIsDefault(), "2", contectNo,
                                addressInfo.getProvinceCode(), addressInfo.getProvinceName(),
                                addressInfo.getRoomName(), addressInfo.getRoomCode(),addressInfo.getPid());
                        doTask(BaseServiceMediator.MANAGER_CAR_ADDRESS_EDIT);
                    } else {
                        if (null != selectedRoom) {

                            String isDefault = "0";
                            LoginResponse user = UserCenter.getCurrentUser();
                            if (null != user){
                                if (UserCenter.isFirstUse(user.getMemberId())){
                                    isDefault = "1";
                                }
                            }
                            requestParams = BaseServiceParams.managerCarAddress(
                                    tagStr, selectedRoom.getAreaCode(),
                                    selectedRoom.getAreaName(), selectedRoom.getCityCode(),
                                    selectedRoom.getCityName(), contectName,
                                    contectNo, addressDetail, isDefault, "1", contectNo,
                                    selectedRoom.getProvinceCode(), selectedRoom.getProvinceName(),
                                    selectedRoom.getRoomName(), selectedRoom.getRoomCode(),"");
                            doTask(BaseServiceMediator.MANAGER_CAR_ADDRESS);
                        }
                    }
                }
                //                requestParams = BaseServiceParams.
                break;
        }
    }


    private void initUI(){
        newAddressContactName.setText(addressInfo.getUserName());
        newAddressContactPhone.setText(addressInfo.getPhoneNo());
        roomAddress.setText(addressInfo.getCityName()+" "+addressInfo.getAreaName()+" "+addressInfo.getRoomName());
        newAddressContactAddress.setText(addressInfo.getDetailAddress());
        String mTag = addressInfo.getAddrType();
        if (!TextUtils.isEmpty(mTag)){
            for (int i = 0; i < mDatas.size(); i++) {
                String selectTag = mDatas.get(i);
                if (selectTag.contentEquals(mTag)){
                    View view =  flowLayout.getChildAt(i).findViewById(R.id.new_address_tag_layout);
                    view.setBackgroundResource(R.drawable.selector_white_layout_select);
                    tagStr = selectTag;
                    lastLayout = (AutoRelativeLayout) view;
                }
            }
        }
    }


    private boolean isLegal() {
        contectName = newAddressContactName.getText().toString();
        contectNo = newAddressContactPhone.getText().toString();
        roomStr = roomAddress.getText().toString();
        addressDetail = newAddressContactAddress.getText().toString();

        if (TextUtils.isEmpty(contectName)) {
            showToast("请填写联系人！");
            return false;
        } else if (TextUtils.isEmpty(contectNo)) {
            showToast("请填写联系手机！");
            return false;
        } else if (TextUtils.isEmpty(roomStr)) {
            showToast("请选择所在地区！");
            return false;
        } else if (TextUtils.isEmpty(addressDetail)) {
            showToast("请填写详细地址！");
            return false;
        } else if (TextUtils.isEmpty(tagStr)) {
            showToast("请选择标签！");
            return false;
        }

        return true;
    }

    @OnClick(R.id.about_score)
    public void onClick() {
        presentController(RoomAddressActivity.class, Const.ROOM_RESULT_CODE);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Const.ROOM_RESULT_CODE) {
            selectedRoom = (Room) data.getSerializableExtra("room");
            LogUtil.e("result--", selectedRoom);
            roomAddress.setText(selectedRoom.getCityName() + " " + selectedRoom.getAreaName() + " " + selectedRoom.getRoomName());

//            if (null != data){
//                selectedRoom = (Room) data.getSerializableExtra("room");
//                LogUtil.e("result--", selectedRoom);
//                roomAddress.setText(selectedRoom.getCityName() + " " + selectedRoom.getAreaName() + " " + selectedRoom.getRoomName());
//                LoginResponse user = UserCenter.getCurrentUser();
//                if (null != user){
//                    UserCenter.setNewMessage();
//                }
//            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void requestSuccess(CoreServiceResponse response) {
        super.requestSuccess(response);
        if (((ManagerCarAddressResponse) response.getResponse()).isSuccess()) {
            if (null != addressInfo){
                showToast("修改成功");
            } else {
                LoginResponse user = UserCenter.getCurrentUser();
                if (null != user){
                    if (UserCenter.isFirstUse(user.getMemberId())){
                        QueryCarAddressInfo info = createDefaultAddressCache(user.getMemberId());
                        CoreEventCenter.postObject(EventConst.FIRST_DEFAULT_ADDRESS_FINISH, info);
//                        CoreEventCenter.postMessage(EventConst.FIRST_DEFAULT_ADDRESS_FINISH, "默认地址填写完毕");
                    }
                }
                showToast("新增地址成功");
            }
            setResult(1);
            finish();
        }
    }


    private QueryCarAddressInfo createDefaultAddressCache(String memberId) {
        QueryCarAddressInfo addressInfo = new QueryCarAddressInfo();
        addressInfo.setAddrType(tagStr);
        addressInfo.setAreaCode(selectedRoom.getAreaCode());
        addressInfo.setAreaName(selectedRoom.getAreaName());
        addressInfo.setCityCode(selectedRoom.getCityCode());
        addressInfo.setCityName(selectedRoom.getCityName());
        addressInfo.setUserName(contectName);
        addressInfo.setPhoneNo(contectNo);
        addressInfo.setDetailAddress(addressDetail);
        addressInfo.setIsDefault("1");
        addressInfo.setProvinceCode(selectedRoom.getProvinceCode());
        addressInfo.setProvinceName(selectedRoom.getProvinceName());
        addressInfo.setRoomName(selectedRoom.getRoomName());
        addressInfo.setRoomCode(selectedRoom.getRoomCode());

        UserCenter.setDefaultAddress(memberId, addressInfo);
        return addressInfo;
    }

    private void saveTagSting () {
        if (null != mDatas && mDatas.size() > 0){
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i< mDatas.size(); i++){
                if (i == mDatas.size()-1){
                    sb.append(mDatas.get(i));
                } else {
                    sb.append(mDatas.get(i)).append("------");
                }
            }
            UserCenter.setTags(user.getMemberId(), sb.toString());
        }
    }
}
